package com.sens.network;

import com.sens.bean.AlipayTrade;
import com.sens.bean.BaseJson;
import com.sens.bean.DeviceInfo;
import com.sens.bean.UserInfo;
import com.sens.common.Base64;
import com.sens.common.JsonUtils;
import com.sens.common.Log;
import com.sens.common.StringUtil;
import com.sens.common.TimeUtil;
import com.sens.tables.AlipayOrder;
import com.sens.tables.BaseOrder;
import com.sens.tables.MybankOrder;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.StringRequest;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cryptotools.CryptoTools;

public class ApiByHttp {
    private static ApiByHttp instance;
    private String host;
    private String channelNumber;
    private String queryTimeInterval;

    private String appid;//TODO
    private int userid;//TODO

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setChannelNumber(String channelNumber) {
        this.channelNumber = channelNumber;
    }

    public void setQueryTimeInterval(String queryTimeInterval) {
        this.queryTimeInterval = queryTimeInterval;
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public int getUserid() {
        return userid;
    }

    public void setUserid(int userid) {
        this.userid = userid;
    }

    public static ApiByHttp getInstance() {
        if (instance == null) instance = new ApiByHttp();
        return instance;
    }

    private ApiByHttp() {
    }

    private String getSecondUrl() {
        if (StringUtil.isEmpty(host)) {
            Log.i("没有设置ip");
            return null;
        }
        String url;
        if (host.startsWith("http")) {
            url = host + "/api/app";
        } else {
            url = "http://" + host + "/api/app";
        }
        return url;
    }

    /**
     * 登录
     */
    public void login(String username, String password, ResponseCallback<UserInfo> responseCallback) {
        String url = getSecondUrl();
        if (url == null) return;
        BeanRequest request = new BeanRequest(UserInfo.class, url, RequestMethod.POST);
        request.add("username", username);
        request.add("password", password);
        request.add("action", "login");
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    /**
     * 回调上线信息
     */
    public void callOnLine(String alipayuserid, String alipayver, String mobilecode, String mobiletype, ResponseCallback<DeviceInfo> responseCallback) {
        String url = getSecondUrl();
        if (url == null) return;
        BaseBeanRequest request = new BaseBeanRequest(UserInfo.class, url, RequestMethod.POST);
        request.add("action", "online");
        request.add("appid", appid);
        request.add("userid", userid);
        request.add("username", alipayuserid);
        request.add("password", alipayver);
        request.add("action", mobilecode);
        request.add("action", mobiletype);
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    /**
     * 上传订单
     */
    public void uploadOrder(BaseOrder order, ResponseCallback<BaseJson> responseCallback) {
        String url = getSecondUrl();
        if (url == null) return;
        BaseBeanRequest request = new BaseBeanRequest(BaseJson.class, url, RequestMethod.POST);
        Map<String, String> map = new HashMap<>();
        map.put("mobilecode", "1247545121");
        if (order instanceof AlipayOrder) {
            AlipayOrder alipayOrder = (AlipayOrder) order;
            map.put("alipayuserid", alipayOrder.getUserId());
            map.put("paytime", alipayOrder.getTime());
            map.put("paynumber", alipayOrder.getTradeNo());
            map.put("checkcode", alipayOrder.getMark());
            map.put("paymoney", alipayOrder.getMoney());
            map.put("paytype", "1");
            map.put("paystatus", "1");
            map.put("paymode", alipayOrder.getMarkType());
        } else if (order instanceof MybankOrder) {
            MybankOrder mybankOrder = (MybankOrder) order;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("alipayuserid", "2088332643335824");
            map.put("paytime", simpleDateFormat.format(new Date(mybankOrder.getTime())));
            map.put("paynumber", mybankOrder.getOrderId());
            map.put("checkcode", "g=" + channelNumber + "&t=" + queryTimeInterval);
            map.put("paymoney", String.valueOf(mybankOrder.getAmount()));
            map.put("paytype", "3");
            map.put("paystatus", "1");
//            map.put("paymode", "1");
        }
        request.add(map);
        request.add("action", "pay");
        request.add("appid", appid);
        try {
            request.add("par", CryptoTools.createLinkStringByGet(map));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 上传订单信息
     */
    public void uploadMybankOrder(MybankOrder mybankOrder, ResponseCallback<String> responseCallback) {
        String url = getMybankUrl();
        if (url == null) return;
        StringRequest request = new StringRequest(url, RequestMethod.GET);
        if (mybankOrder != null) {
            request.add("MY18DT", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(mybankOrder.getTime())));
            request.add("MY18oid", mybankOrder.getOrderId());
            request.add("MY18M", mybankOrder.getAmount());
            request.add("MY18PT", "支付宝");
            request.add("MY18Zt", "交易成功");
            request.add("g", channelNumber);
            request.add("t", queryTimeInterval);
            request.add("b", 2);
        } else {
            request.add("action", "online");
        }
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    private String getMybankUrl() {
        if (StringUtil.isEmpty(host)) {
            Log.i("没有设置ip");
            return null;
        }
        String url;
        if (host.startsWith("http")) {
            url = host + "/AliBankPayRes.ashx";
        } else {
            url = "http://" + host + "/AliBankPayRes.ashx";
        }
        return url;
    }

    private String getAlipayUrl() {
        if (StringUtil.isEmpty(host)) {
            Log.i("没有设置ip");
            return null;
        }
        String url;
        if (host.startsWith("http")) {
            url = host + "/AliPayResultHandler.ashx";
        } else {
            url = "http://" + host + "/AliPayResultHandler.ashx";
        }
        return url;
    }

    /**
     * 上传订单信息
     */
    public void uploadAlipayOrder(AlipayOrder alipayOrder, ResponseCallback<BaseJson> responseCallback) {
        String url = getAlipayUrl();
        if (url == null) return;
        BaseBeanRequest request = new BaseBeanRequest(BaseJson.class, url, RequestMethod.POST);
        if (alipayOrder != null) {
            request.add("action", "pay");
            request.add("paytime", alipayOrder.getTime());
            request.add("paynumber", alipayOrder.getTradeNo());
            request.add("checkcode", alipayOrder.getMark());
            request.add("paymoney", alipayOrder.getMoney());
            request.add("paytype", alipayOrder.getPayType());
            request.add("paystatus", 1);
        } else {
            request.add("action", "online");
        }
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    /**
     * 上传错误订单日志
     */
    public void uploadAlipayLog(AlipayOrder alipayOrder, BaseJson respose, ResponseCallback<BaseJson> responseCallback) {
        String url = getAlipayUrl();
        if (url == null) return;
        BaseBeanRequest request = new BaseBeanRequest(BaseJson.class, url, RequestMethod.POST);
        if (alipayOrder != null) {
            HashMap<String, Object> map = new HashMap<>(9);
            map.put("status", respose.getStatus());
            map.put("msg", respose.getMsg());
            map.put("code", respose.getCode());
            map.put("paytime", alipayOrder.getTime());
            map.put("paynumber", alipayOrder.getTradeNo());
            map.put("checkcode", alipayOrder.getMark());
            map.put("paymoney", alipayOrder.getMoney());
            map.put("paytype", 1);
            map.put("paystatus", 1);
            request.add("action", "log");
            request.add("text", JsonUtils.parserBean2Json(map));
        }
        NoHttpUtil.getInstance().add(request, responseCallback);
    }

    /**
     * 查询订单信息
     * 失败数据返回日志提交
     * 如果处理失败的订单数据，
     * 再补发3次后依然错误，
     * 需要连同发送数据一同记录保存为json字符串格式到失败数据库中，
     * 并每隔1小时将失败日志发送给服务器。
     * 已发送的日志将不再发送.
     */
    public void queryAlipayOrder(int pageSize, int pageNum, String cookie, ResponseCallback<AlipayTrade> responseCallback) {
        long current = System.currentTimeMillis();
        long beginTime = current - 864000000;
        //https://mbillexprod.alipay.com/enterprise/simpleTradeOrderQuery.json?beginTime=1544951291798&limitTime=1545815291798&pageSize=20&pageNum=1&channelType=ALL
        String url = new String(Base64.decode("aHR0cHM6Ly9tYmlsbGV4cHJvZC5hbGlwYXkuY29tL2VudGVycHJpc2Uvc2ltcGxlVHJhZGVPcmRlclF1ZXJ5Lmpzb24")) + beginTime + "&limitTime=" + current + "&pageSize=" + pageSize + "&pageNum=" + pageNum + "&channelType=ALL";
        BaseBeanRequest beanRequest = new BaseBeanRequest(AlipayTrade.class, url);
        beanRequest.setHeader(new String(Base64.decode("Q29va2ll")), cookie);
        String currentDate = TimeUtil.getCurrentDate();
        beanRequest.setHeader(new String(Base64.decode("UmVmZXJlcg")), new String(Base64.decode("aHR0cHM6Ly9yZW5kZXIuYWxpcGF5LmNvbS9wL3ovbWVyY2hhbnQtbWdudC9zaW1wbGUtb3JkZXIuaHRtbD9iZWdpblRpbWU9")) + currentDate + "&endTime=" + currentDate + "&fromBill=true&channelType=ALL");
        NoHttpUtil.getInstance().add(beanRequest, responseCallback);
    }
}